#include "flee.h"
#include "Ai.hpp"
#include "idle.h"
#include <iostream>



Flee::Flee(Fruit *idP){
    type = T_FLEE;
    idParent = idP;
    age=0;
}


bool Flee::execute() {

    //si objets en main
    if(idParent->sugar + idParent->vitamins > 0)
    {
        //si assez pres du point de depose, deposer
        int ret = idParent->stockSugar();
        cout << "FLEE stock " << ai.api->decode(ret) << endl;

        if(ret==OK);
        //sinon
        else
        {
            //aller au point de depose
            path.clear();
            pf.start = idParent->position;
            pf.end = getFreeSpaceAround(ai.world.ourSugarBowl.position);

            if(pf.compute(&path,0,0)==false) {
                return false; //On fonce comme des brutes donc on need pas tout ça :D

            }            {
                list<map_chunk*>::iterator it = path.begin();
                for( int i = 0; i < idParent->speed; i++ ) if( it != path.end() )it++;
                if( it == path.end() ) it--;
                //if( (*it) == pf.end ) it--;
                int ret = idParent->move((*it)->X_coord, (*it)->Y_coord );
                ai.world.printInfos();
                /*cout << "FLEE Dest : " << (*it)->X_coord;
                cout << "," << (*it)->Y_coord << endl;
                cout << "FLEE move " << ai.api->decode(ret) << endl;*/
                if(ret!=OK) return false;
            }
        }
    }
    //sinon, si pas max de vie
    else if(idParent->life < idParent->maxLife)
    {

        //si assez pres du jus de fruit //se redonner de la vie
        int ret = idParent->drinkJuice();
        if(ret == LIFE_GAINED || ret == DEFENSE_GAINED || ret == HEALTHY);

        //sinonaller au jus de fruit
        else
        {
            path.clear();
            pf.start = idParent->position;
            pf.end = ai.world.ourJuiceBarrel.position;
            if(pf.compute(&path,0,0)==false) {
                return false; //On fonce comme des brutes donc on need pas tout ça :D

            }
            {
                list<map_chunk*>::iterator it = path.begin();
                for( int i = 0; i < idParent->speed; i++ ) if( it != path.end() )it++;
                if( it == path.end() ) it--;
                if( (*it) == pf.end ) it--;
                int ret = idParent->move((*it)->X_coord, (*it)->Y_coord );
                if(ret!=OK) return false;
            }
        }

    }
    //sinon (comme tout va bien)
    else
    {
        //passer en idle
        delete idParent->task;
        idParent->task = new Idle();
        return false;
    }

    return true;
}


